<template>
  <div class="layout-padding">
    <div class="layout-padding-auto layout-padding-view">
      <!-- 搜索区域 -->
      <el-row v-show="showSearch">
        <el-form :model="state.queryForm" ref="queryRef" :inline="true" @keyup.enter="getDataList">
          <el-form-item>
            <el-select v-model="state.queryForm.brandId" placeholder="选择品牌" @change="onBrandChange">
              <el-option v-for="(item, index) in brandList"
                         :key="index"
                         :value="item.brandId"
                         :label="item.brandName"/>
            </el-select>
          </el-form-item>
          <el-form-item prop="modelId">
            <el-select v-model="state.queryForm.modelId" placeholder="选择型号" >
              <el-option v-for="(item, index) in modelList"
                         :key="index"
                         :value="item.modelId"
                         :label="item.modelName"/>
            </el-select>
          </el-form-item>
          <el-form-item prop="status">
            <el-select v-model="state.queryForm.status" placeholder="选择状态" style="width:100%">
              <el-option v-for="(item, index) in status"
                         :key="index"
                         :value="item.value"
                         :label="item.label"/>
            </el-select>
          </el-form-item>
          <el-form-item prop="sellingPrice" >
            <el-input
                v-model="state.queryForm.minPrice"
                placeholder="售卖价格"
                style="width: 120px"
                type="text"
            />
            <span style="margin: 0 8px;">---</span>
            <el-input
                v-model="state.queryForm.maxPrice"
                placeholder="售卖价格"
                style="width: 120px"
                type="text"
            />
          </el-form-item>
          <el-form-item>
            <el-button icon="search" type="primary" @click="getDataList">
              查询
            </el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-row>

      <!-- 标签筛选 -->
      <el-row>
        <el-space wrap :size="8" class="mb8">
          <button
              class="label-item"
              style="background-color: #6d6b6b; color: #000000;"
              @click="clearLabelFilter"
          >
            不限
          </button>
          <button
              v-for="(item, index) in labelList"
              :key="index"
              class="label-item"
              :style="{backgroundColor: item.color, color: '#000000'}"
              @click="selectLabel(item.labelId)"
          >
            {{ item.labelName }}
          </button>
        </el-space>
      </el-row>

      <!-- 操作按钮 -->
      <el-row>
        <div class="mb8" style="width: 100%">
          <el-button
              v-if="!isGridView"
              icon="folder-add"
              type="primary"
              class="ml10"
              @click="formDialogRef.openDialog()"
              v-auth="'yu_carInfo_add'">
            新 增
          </el-button>
          <el-button
              v-if="!isGridView"
              plain :disabled="multiple"
              icon="Delete" type="primary"
              v-auth="'yu_carInfo_del'"
              @click="handleDelete(selectObjs)">
            删除
          </el-button>
          <!-- 切换视图模式按钮 -->
          <el-button type="primary" class="ml10" @click="toggleViewMode">
            <template v-if="isGridView">列表模式</template>
            <template v-else>方格模式</template>
          </el-button>
        </div>
      </el-row>

      <!-- 列表视图 -->
      <el-table
          v-if="!isGridView"
          :data="state.dataList"
          v-loading="state.loading"
          border
          :cell-style="tableStyle.cellStyle"
          :header-cell-style="tableStyle.headerCellStyle"
          @selection-change="selectionChangHandle"
          @sort-change="sortChangeHandle"
      >
        <el-table-column type="selection" width="40" align="center" />
        <el-table-column prop="carCode" label="车辆编号" show-overflow-tooltip width="180"/>
        <el-table-column prop="brandName" label="品牌"  show-overflow-tooltip width="100"/>
        <el-table-column prop="modelName" label="型号"  show-overflow-tooltip width="100"/>
        <el-table-column prop="styleName" label="款式"  show-overflow-tooltip width="100"/>
        <el-table-column prop="carDrive" label="驱动" show-overflow-tooltip width="100">
          <template #default="scope">
            <dict-tag :options="car_drive" :value="scope.row.carDrive"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column prop="emissionStandards" label="排放标准" show-overflow-tooltip width="100">
          <template #default="scope">
            <dict-tag :options="emission_standards" :value="scope.row.emissionStandards"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column prop="carColer" label="颜色" show-overflow-tooltip width="100">
          <template #default="scope">
            <dict-tag :options="car_coler" :value="scope.row.carColer"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column prop="cearbox" label="变速箱" show-overflow-tooltip width="100">
          <template #default="scope">
            <dict-tag :options="cearbox" :value="scope.row.cearbox"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column prop="seatsNums" label="座位数" show-overflow-tooltip width="100">
          <template #default="scope">
            <dict-tag :options="seats_nums" :value="scope.row.seatsNums"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column prop="fuelType" label="燃料类型" show-overflow-tooltip width="100">
          <template #default="scope">
            <dict-tag :options="fuel_type" :value="scope.row.fuelType"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column prop="series" label="车系"  show-overflow-tooltip width="100">
          <template #default="scope">
            <dict-tag :options="series" :value="scope.row.series" />
          </template>
        </el-table-column>
        <el-table-column prop="costOfCollection" label="收车成本"  show-overflow-tooltip width="100"/>
        <el-table-column prop="sellingPrice" label="售价"  show-overflow-tooltip width="100"/>
        <el-table-column prop="status" label="状态"  show-overflow-tooltip width="100">
          <template #default="scope">
            <dict-tag :options="status" :value="scope.row.status" ></dict-tag>
          </template>
        </el-table-column>
        <el-table-column prop="factoryTime" label="出厂时间"  show-overflow-tooltip width="100"/>
        <el-table-column prop="lableId" label="标签" show-overflow-tooltip width="100">
          <template #default="scope">
            <div
                class="labels"
                :style="{backgroundColor: scope.row.color}"
            >
              {{ scope.row.labelName }}
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="isSelling" label="是否已售"  show-overflow-tooltip width="100">
          <template #default="scope">
            <dict-tag :options="isSelling" :value="scope.row.isSelling" ></dict-tag>
          </template>
        </el-table-column>
        <el-table-column prop="pictures" label="图片" show-overflow-tooltip width="100">
          <template #default="scope">
            <el-image
                v-if="scope.row.pictures"
                :src="formatImageUrl(scope.row.pictures)"
                :preview-src-list="[formatImageUrl(scope.row.pictures)]"
                preview-teleported
                fit="cover"
                style="width: 50px; height: 50px; border-radius: 4px; cursor: pointer;"
                lazy
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注"  show-overflow-tooltip width="100"/>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button icon="edit-pen" text type="primary" v-auth="'yu_carInfo_edit'"
                       @click="formDialogRef.openDialog(scope.row.infoId)">编辑</el-button>
            <el-button icon="delete" text type="primary" v-auth="'yu_carInfo_del'" @click="handleDelete([scope.row.infoId])">删除</el-button>
            <el-button
                icon="crop"
                text
                type="primary"
                v-auth="'yu_carInfo_edit'"
                @click="handleStatusChange(scope.row)"
            >
              {{ scope.row.status != 1 ? '上架' : '下架' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 方格视图 -->
      <grid-view
          v-if="isGridView"
          :data-list="state.dataList"
          :on-refresh="getDataList"
          :on-edit="handleGridEdit"
      ></grid-view>

      <!-- 分页 -->
      <pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" v-bind="state.pagination" />
    </div>

    <!-- 编辑、新增对话框 -->
    <form-dialog ref="formDialogRef" @refresh="getDataList(false)" />

  </div>
</template>

<script setup lang="ts" name="systemCarInfo">
import { BasicTableProps, useTable } from "/@/hooks/table";
import { fetchList, delObjs, getBrands, getModels, putObj } from "/@/api/yu/carInfo";
import { useMessage, useMessageBox } from "/@/hooks/message";
import { useDict } from '/@/hooks/dict';
import DictTag from "/@/components/DictTag/index.vue";
import { getAllLabel } from "/@/api/yu/carInfo";

// 引入组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));
const GridView = defineAsyncComponent(() => import('./grid-view.vue'));

// 定义查询字典
const { car_coler, seats_nums, emission_standards, cearbox, fuel_type, car_drive, series, status, isSelling } =
    useDict('car_coler', 'seats_nums', 'emission_standards', 'cearbox', 'fuel_type', 'car_drive', 'series', 'status', 'isSelling')

// 定义变量内容
const formDialogRef = ref()
const queryRef = ref()
const showSearch = ref(true)
const selectObjs = ref([]) as any
const multiple = ref(true)
const brandList = ref<any[]>([])
const modelList = ref<any[]>([])
const labelList = ref<any[]>([]);

// 视图模式切换变量
const isGridView = ref(false);

const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: {
    brandId: '',
    modelId: '',
    minPrice: '',
    maxPrice: '',
    lableId: ''
  },
  pageList: fetchList
})

// 切换视图模式
const toggleViewMode = () => {
  isGridView.value = !isGridView.value;
};

// 方格视图编辑处理
const handleGridEdit = (id: string) => {
  formDialogRef.value.openDialog(id);
};

// 状态切换处理（上架/下架）
const handleStatusChange = async (row: any) => {
  try {
    await useMessageBox().confirm(`确定要${row.status != 1 ? '上架' : '下架'}该车辆吗？`);
  } catch {
    return;
  }
  try {
    await putObj({
      infoId: row.infoId,
      status: row.status != 1 ? 1 : 2
    });
    useMessage().success(`${row.status != 1 ? '上架' : '下架'}成功`);
    getDataList();
  } catch (err: any) {
    useMessage().error(err.msg || `${row.status != 1 ? '上架' : '下架'}失败`);
  }
};

// 图片URL格式化
const formatImageUrl = (url: string) => {
  if (!url) return '';
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url;
  }
  const baseURL = import.meta.env.VITE_IMAGE_BASE_URL || import.meta.env.VITE_ADMIN_PROXY_PATH || '';
  return baseURL + (url.startsWith('/') ? url : '/' + url);
};

// 标签选择
const selectLabel = (labelId: number) => {
  state.queryForm.lableId = labelId;
  getDataList();
};

// 清除标签筛选
const clearLabelFilter = () => {
  state.queryForm.lableId = '';
  getDataList();
};

// 获取所有标签列表
const fetchAllLabels = async () => {
  try {
    const res = await getAllLabel();
    labelList.value = res.data || [];
  } catch (error) {
    console.error('获取标签列表失败:', error);
  }
};

// 获取品牌列表
const getBrandList = async () => {
  try {
    const { data } = await getBrands("");
    brandList.value = data;
  } catch (error) {
    useMessage().error('获取品牌列表失败');
  }
};

// 品牌变更事件
const onBrandChange = async (brandId: number) => {
  state.queryForm.modelId = '';
  modelList.value = [];
  if (!brandId) return;
  try {
    const res = await getModels(brandId);
    modelList.value = res.data || [];
  } catch (error) {
    console.error('获取型号列表失败', error);
    useMessage().error('获取型号列表失败');
  }
};

// table hook
const {
  getDataList,
  currentChangeHandle,
  sizeChangeHandle,
  sortChangeHandle,
  tableStyle
} = useTable(state)

// 清空搜索条件
const resetQuery = () => {
  queryRef.value?.resetFields();
  state.queryForm.minPrice = '';
  state.queryForm.maxPrice = '';
  state.queryForm.lableId = '';
  state.queryForm.brandId = '';
  modelList.value = []
  selectObjs.value = []
  getDataList();
  getBrandList();
}

// 多选事件
const selectionChangHandle = (objs: { infoId: string }[]) => {
  selectObjs.value = objs.map(({ infoId }) => infoId);
  multiple.value = !objs.length;
};

// 删除操作
const handleDelete = async (ids: string[]) => {
    await useMessageBox().confirm('此操作将永久删除');
    await delObjs(ids);
    getDataList();
    useMessage().success('删除成功');
};

// 初始化加载
onMounted(() => {
  getBrandList();
  fetchAllLabels();
});
</script>

<style scoped>
/* 标签样式 */
.label-item {
  width: 75px;
  font-size: 13px;
  font-weight: 500;
  height: 30px;
  padding: 4px 10px;
  border-radius: 4px;
  min-width: 50px;
  text-align: center;
  border: none;
  cursor: pointer;
}

/* 图片占位符样式 */
.image-slot {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
}
</style>
